package com.xywl.escort.view.order.search

import android.content.Context
import android.os.Bundle
import android.support.v4.widget.SwipeRefreshLayout
import android.support.v7.widget.LinearLayoutManager
import android.text.TextUtils
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.inputmethod.EditorInfo
import android.view.inputmethod.InputMethodManager
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.raizlabs.android.dbflow.sql.language.Delete
import com.raizlabs.android.dbflow.sql.language.SQLite
import com.raizlabs.android.dbflow.sql.language.Select
import com.trello.rxlifecycle2.LifecycleTransformer
import com.xywl.escort.R
import com.xywl.escort.adapter.PurchaseOrderAdapter
import com.xywl.escort.adapter.SearchOrderAdapter
import com.xywl.escort.base.BaseActivity
import com.xywl.escort.bean.PurchaseOrderDetailBean
import com.xywl.escort.bean.PurchaseOrderListResp
import com.xywl.escort.db.SearchModel
import com.xywl.escort.db.SearchModel_Table
import com.xywl.escort.utils.ToastUtil
import dagger.android.AndroidInjection
import kotlinx.android.synthetic.main.activity_search_order.*
import kotlinx.android.synthetic.main.layout_empty_view.view.*
import java.util.*
import javax.inject.Inject

@Route(path = "/xy/order/search")
class SearchOrderActivity : BaseActivity(), SearchOrderContract.View, SwipeRefreshLayout.OnRefreshListener {
    private val mList = ArrayList<String>()
    private val mSearchList = ArrayList<PurchaseOrderDetailBean>()
    private lateinit var mSearchOrderAdapter: SearchOrderAdapter
    private lateinit var mAdapter: PurchaseOrderAdapter

    private var pageNum = 1
    private var isEnd: Boolean = false

    @Inject
    lateinit var mPresenter: SearchOrderContract.Presenter

    private var mSearchString: String = ""

    override fun onCreate(savedInstanceState: Bundle?) {
        AndroidInjection.inject(this)
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_search_order)
        initView()
        initData()
        addListener()

        mPresenter.takeView(this)
    }

    private fun initView() {
        val layoutManage = LinearLayoutManager(this)
        recycler_history.layoutManager = layoutManage
        mSearchOrderAdapter = SearchOrderAdapter(R.layout.item_order_search_layout, mList)
        recycler_history.adapter = mSearchOrderAdapter

        val emptyView = LayoutInflater.from(this).inflate(R.layout.layout_empty_view, null)
        emptyView.tv_empty.text = getString(R.string.empty_order_search)
        mSearchOrderAdapter.emptyView = emptyView
        val headerView = layoutInflater.inflate(R.layout.item_order_search_header, recycler_history.parent as ViewGroup, false)
        mSearchOrderAdapter.setHeaderView(headerView)

        val searchLayoutManager = LinearLayoutManager(this)
        recycler_search_result.layoutManager = searchLayoutManager
        mAdapter = PurchaseOrderAdapter(R.layout.item_order_purchase, mSearchList)
        recycler_search_result.adapter = mAdapter
        val emptySearchView = LayoutInflater.from(this).inflate(R.layout.layout_empty_view, null)
        mAdapter.emptyView = emptySearchView

        swipeLayout.setOnRefreshListener(this)
        swipeLayout.setColorSchemeResources(R.color.colorAccent, R.color.colorPrimary, R.color.aid_prompt_color, R.color.colorBackground)

        mAdapter.setOnLoadMoreListener({
            swipeLayout.isEnabled = false
            recycler_search_result.postDelayed({
                swipeLayout.isEnabled = false
                if (isEnd) {
                    //数据全部加载完毕
                    mAdapter.loadMoreEnd()
                    swipeLayout.isEnabled = true
                } else {
                    //成功获取更多数据
                    mPresenter.loadOrder(-1, pageNum, "")
                }
            }, 200)
        }, recycler_search_result)
    }

    private fun initData() {
        val searchBeanList = SQLite.select().from(SearchModel::class.java)
                .limit(10)
                .orderBy(SearchModel_Table.id, false)
                .queryList()
        for (i in searchBeanList.indices) {
            mList.add(searchBeanList[i].name)
        }
        if (mList.size == 0) {
            btn_clear.visibility = View.GONE
        }
        mSearchOrderAdapter.setNewData(mList)
    }

    private fun addListener() {
        tv_search.setOnClickListener {
            search(edit_search.text.toString().trim())
        }

        edit_search.setOnEditorActionListener { _, actionId, _ ->
            when (actionId) {
                EditorInfo.IME_ACTION_SEARCH -> search(edit_search.text.toString().trim())
                else -> {
                }
            }
            true
        }

        mSearchOrderAdapter.setOnItemClickListener { _, _, position ->
            if (mList.size > 0 && mList.size > position) {
                search(mList[position])
            }
        }

        mAdapter.setOnItemClickListener { _, _, position ->
            val dataBean = mSearchList[position]
            ToastUtil.showTip(this@SearchOrderActivity, "dataBean=$dataBean")
            ARouter.getInstance()
                    .build("/xy/order/purchase/detail")
                    .withString("orderId", dataBean.id)
                    .navigation()
        }

        btn_clear.setOnClickListener {
            Delete.table(SearchModel::class.java)
            mSearchOrderAdapter.replaceData(ArrayList<String>())
            mSearchOrderAdapter.notifyDataSetChanged()
        }
    }

    private fun search(keyword: String?) {
        if (!TextUtils.isEmpty(keyword)) {
            val searchModel = Select().from(SearchModel::class.java).where(SearchModel_Table.name.`is`(keyword)).querySingle()
            if (null == searchModel) {
                val searchBean = SearchModel()
                searchBean.name = keyword
                searchBean.save()
            }

            hideKeyboard()
            recycler_history.visibility = View.GONE
            progress_bar.visibility = View.VISIBLE
            swipeLayout.visibility = View.VISIBLE
            btn_clear.visibility = View.GONE
            mAdapter.setEnableLoadMore(false)

            pageNum = 1
            mSearchString = keyword!!
            mPresenter.loadOrder(-1, pageNum, keyword)
        }
    }

    override fun isActive(): Boolean {
        return false
    }

    override fun <T : Any?> bindToLife(): LifecycleTransformer<T> {
        return this.bindToLifecycle()
    }

    override fun doBack(v: View?) {
        finish()
    }

    override fun onRefresh() {
        pageNum = 1
        mAdapter.setEnableLoadMore(false)
        mPresenter.loadOrder(-1, pageNum, mSearchString)
    }

    override fun loadOrderSuccess(dataBean: PurchaseOrderListResp.DataBean?) {
        swipeLayout.isRefreshing = false
        progress_bar.visibility = View.GONE
        swipeLayout.visibility = View.VISIBLE
        if (pageNum == 1) {
            mSearchList.clear()
        }
        if (pageNum >= dataBean!!.pages) {
            isEnd = true
        } else {
            isEnd = false
            pageNum += 1
        }
        mSearchList.addAll(dataBean.list)
        mAdapter.setNewData(mSearchList)
        mAdapter.loadMoreComplete()
        swipeLayout.isEnabled = true
    }

    override fun loadOrderFailure() {
        swipeLayout.isRefreshing = false
        progress_bar.visibility = View.GONE
        recycler_search_result.visibility = View.VISIBLE
    }

    private fun hideKeyboard() {
        val imm = this.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
        if (imm.isActive && this.currentFocus != null) {
            if (this.currentFocus.windowToken != null) {
                imm.hideSoftInputFromWindow(this.currentFocus.windowToken, InputMethodManager.HIDE_NOT_ALWAYS)
            }
        }
    }
}
